<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>卷烟甜味知识服务平台</title>
  <!-- 引入Tailwind CSS -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- 引入Font Awesome -->
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <!-- 配置Tailwind自定义颜色和字体 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#1E40AF', // 深蓝色作为主色调
            secondary: '#3B82F6', // 中蓝色作为辅助色
            accent: '#93C5FD', // 浅蓝色作为强调色
            neutral: '#F1F5F9', // 浅灰色作为中性色
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <!-- 自定义工具类 -->
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .bg-blur {
        backdrop-filter: blur(8px);
      }
      .transition-custom {
        transition: all 0.3s ease;
      }
      .shadow-custom {
        box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
      }
    }
  </style>
</head>
<body class="font-sans antialiased text-gray-800 min-h-screen overflow-x-hidden">
  <!-- 登录页面 -->
  <div id="login-page" class="min-h-screen flex flex-col">
    <!-- 背景图 -->
    <div class="absolute inset-0 z-0">
      <img src="https://picsum.photos/id/1060/1920/1080" alt="登录背景" class="w-full h-full object-cover">
      <div class="absolute inset-0 bg-black/40"></div>
    </div>

    <!-- 登录容器 -->
    <div class="relative z-10 flex-1 flex flex-col items-center justify-center px-4 sm:px-6 lg:px-8">
      <!-- 标题 -->
      <div class="mb-10 text-center">
        <h1 class="text-[clamp(1.8rem,5vw,3rem)] font-bold text-white tracking-tight mx-auto ">
          欢迎使用卷烟甜味知识服务平台！
        </h1>
        <p class="mt-3 text-blue-100 max-w-md mx-auto ">
          专业的卷烟甜味知识查询与分析服务，助力您的研究与工作！
        </p>
      </div>

      <!-- 登录表单卡片 -->
      <div class="w-full max-w-md bg-white/90 bg-blur rounded-xl shadow-custom p-8 transform transition-custom hover:scale-[1.01]">
        <form id="login-form" class="space-y-6">
          <!-- 账号输入 -->
          <div>
            <label for="username" class="block text-sm font-medium text-gray-700 mb-1">账号</label>
            <div class="relative">
              <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <i class="fa fa-user text-gray-400"></i>
              </div>
              <input type="text" id="username" name="username" required
                class="pl-10 block w-full rounded-lg border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/20 transition-custom py-3 border"
                placeholder="请输入账号">
            </div>
          </div>

          <!-- 密码输入 -->
          <div>
            <label for="password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
            <div class="relative">
              <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <i class="fa fa-lock text-gray-400"></i>
              </div>
              <input type="password" id="password" name="password" required
                class="pl-10 block w-full rounded-lg border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/20 transition-custom py-3 border"
                placeholder="请输入密码">
              <button type="button" id="toggle-password" class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600">
                <i class="fa fa-eye-slash"></i>
              </button>
            </div>
          </div>

          <!-- 登录按钮 -->
          <div>
            <button type="submit"
              class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-3 px-4 rounded-lg transition-custom focus:outline-none focus:ring-2 focus:ring-primary/50">
              登录
            </button>
          </div>
        </form>

        <!-- 其他功能链接 -->
        <div class="mt-6 space-y-3">
          <div class="flex justify-center space-x-6">
            <button id="forgot-password" class="text-sm text-secondary hover:text-primary transition-custom">
              <i class="fa fa-key mr-1"></i> 修改密码
            </button>
            <button id="register" class="text-sm text-secondary hover:text-primary transition-custom">
              <i class="fa fa-user-plus mr-1"></i> 注册新用户
            </button>
          </div>
        </div>
      </div>

      <!-- 页脚 -->
      <div class="mt-10 text-center text-white/80 text-sm">
        <p>© 2025 卷烟甜味知识服务平台 版权所有@云南大学</p>
      </div>
    </div>
  </div>

  <!-- 服务页面 -->
  <div id="service-page" class="hidden min-h-screen flex flex-col">
    <!-- 背景图 -->
    <div class="absolute inset-0 z-0">
      <img src="https://picsum.photos/id/1060/1920/1080" alt="服务背景" class="w-full h-full object-cover">
      <div class="absolute inset-0 bg-black/30"></div>
    </div>

    <!-- 主内容区 -->
    <div class="relative z-10 flex-1 container mx-auto px-4 py-8">
      <div class="flex flex-col lg:flex-row gap-6">
        <!-- 左侧列：平台简介 (1/4宽度) -->
        <div class="lg:w-1/4 bg-white/80 bg-blur rounded-xl shadow-custom p-6 h-fit">
          <h2 class="text-xl font-bold text-primary mb-4 flex items-center">
            <i class="fa fa-info-circle mr-2"></i>平台简介
          </h2>
          <div class="space-y-4 text-gray-700">
            <p>卷烟甜味知识服务平台是一个专业的卷烟相关甜味知识查询系统，旨在为研究人员、从业人员提供便捷的信息检索服务。</p>
            <p>平台收录了致甜成分名称、实验方法、烟叶类型、评吸方式、相对甜度、添加方法、致甜成分香气等多方面的专业知识，支持多种查询方式。</p>
            <p>您可以通过自然语言提问，快速获取相关的专业信息，助力您的研究与工作。</p>

            <div class="mt-6 pt-4 border-t border-gray-200">
              <h3 class="font-semibold text-primary mb-2">使用提示</h3>
              <ul class="list-disc pl-5 space-y-1 text-sm">
                <li>请输入清晰、具体的问题</li>
                <li>可参考右侧提供的问题示例</li>
                <li>系统会自动保存您的查询历史</li>
                <li>部分内容平台可能暂未收录，如有需要请耐心等待知识更新</li>
              </ul>
            </div>
          </div>
        </div>

        <!-- 中间列：交互界面 (1/2宽度) -->
        <div class="lg:w-2/4 flex flex-col gap-8">
          <!-- 上部分：问题输入区 -->
          <div class="bg-white/80 bg-blur rounded-xl shadow-custom p-6 h-auto min-h-[140px]">
            <h2 class="text-xl font-bold text-primary mb-4 flex items-center">
              <i class="fa fa-question-circle mr-2"></i>问题查询
            </h2>
            <form id="query-form" class="space-y-4">
              <div>
                <textarea id="question-input" rows="2"
                  class="w-full px-4 py-3 rounded-lg border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/20 transition-custom border resize-none"
                  placeholder="请输入您想查询的问题，例如：山梨醇的相对甜度是多少？"></textarea>
              </div>
              <div class="flex justify-end">
                <button type="submit"
                  class="bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-lg transition-custom focus:outline-none focus:ring-2 focus:ring-primary/50 flex items-center">
                  <i class="fa fa-search mr-2"></i>查询
                </button>
              </div>
            </form>
          </div>

          <!-- 下部分：回答输出区 -->
          <div class="bg-white/80 bg-blur rounded-xl shadow-custom p-6 flex-1 overflow-y-auto">
            <h2 class="text-xl font-bold text-primary mb-4 flex items-center">
              <i class="fa fa-comment mr-2"></i>查询结果
            </h2>
            <div id="answer-container" class="max-h-64 p-4 bg-white/80 rounded-lg border border-gray-200 overflow-y-auto">
              <div class="text-gray-500 text-center py-12">
                <i class="fa fa-lightbulb-o text-4xl mb-3 text-gray-300"></i>
                <p>请输入问题并点击查询按钮获取结果</p>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧列：示例和历史记录 (1/4宽度) -->
        <div class="lg:w-1/4 flex flex-col gap-6">
          <!-- 上窗口：问题示例 -->
          <div class="bg-white/80 bg-blur rounded-xl shadow-custom p-6">
            <h2 class="text-xl font-bold text-primary mb-4 flex items-center">
              <i class="fa fa-list-alt mr-2"></i>问题示例
            </h2>
            <div class="space-y-3 max-h-64 overflow-y-auto overflow-y-auto pr-2">
              <div class="p-3 bg-blue-50 rounded-lg border border-blue-100 hover:bg-blue-100 cursor-pointer transition-custom example-question">
                <p class="text-sm">天然植物提取物有什么文献？</p>
              </div>
              <div class="p-3 bg-blue-50 rounded-lg border border-blue-100 hover:bg-blue-100 cursor-pointer transition-custom example-question">
                <p class="text-sm">麦芽酚怎么添加？</p>
              </div>
              <div class="p-3 bg-blue-50 rounded-lg border border-blue-100 hover:bg-blue-100 cursor-pointer transition-custom example-question">
                <p class="text-sm">山梨醇的相对甜度是多少？</p>
              </div>
              <div class="p-3 bg-blue-50 rounded-lg border border-blue-100 hover:bg-blue-100 cursor-pointer transition-custom example-question">
                <p class="text-sm">糠醛这个成分在哪些文献中提到了？</p>
              </div>
              <div class="p-3 bg-blue-50 rounded-lg border border-blue-100 hover:bg-blue-100 cursor-pointer transition-custom example-question">
                <p class="text-sm">《罗望子提取物挥发性成分分析及其应用_覃荣》中提到了哪些致甜成分？</p>
              </div>
              <div class="p-3 bg-blue-50 rounded-lg border border-blue-100 hover:bg-blue-100 cursor-pointer transition-custom example-question">
                <p class="text-sm">DDMP-5-肉桂酸酯的甜味持续性如何？</p>
              </div>
              <div class="p-3 bg-blue-50 rounded-lg border border-blue-100 hover:bg-blue-100 cursor-pointer transition-custom example-question">
                <p class="text-sm">麦芽酚的评吸方式？</p>
              </div>
            </div>
          </div>

          <!-- 下窗口：查询历史 -->
          <div class="bg-white/80 bg-blur rounded-xl shadow-custom p-6 flex-1">
            <h2 class="text-xl font-bold text-primary mb-4 flex items-center">
              <i class="fa fa-history mr-2"></i>查询历史
            </h2>
            <div id="history-container" class="max-h-32 overflow-y-auto space-y-3 pr-2">
              <div class="text-gray-400 text-center py-6 text-sm">
                暂无查询历史
              </div>
            </div>
            <button id="clear-history" class="mt-4 text-sm text-gray-500 hover:text-red-500 transition-custom flex items-center">
              <i class="fa fa-trash-o mr-1"></i> 清空历史
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 退出按钮 -->
    <button id="logout-btn" class="fixed bottom-6 right-6 bg-red-500 hover:bg-red-600 text-white rounded-full p-3 shadow-lg transition-custom z-20">
      <i class="fa fa-sign-out text-xl"></i>
    </button>

    <!-- 页脚 -->
    <div class="relative z-10 text-center text-white/80 text-sm py-4">
      <p>© 2025 卷烟知识服务平台 版权所有@云南大学</p>
    </div>
  </div>

  <!-- 验证码模态框 -->
  <div id="verify-modal" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center hidden">
    <div class="bg-white rounded-xl shadow-custom p-6 w-full max-w-md">
      <h3 class="text-lg font-bold text-primary mb-4" id="modal-title">短信验证</h3>
      <form id="verify-form" class="space-y-4">
        <div>
          <label for="phone" class="block text-sm font-medium text-gray-700 mb-1">手机号码</label>
          <input type="tel" id="phone" name="phone" required
            class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/20 transition-custom py-2 border"
            placeholder="请输入手机号码">
        </div>
        <div class="flex gap-2">
          <div class="flex-1">
            <label for="verify-code" class="block text-sm font-medium text-gray-700 mb-1">验证码</label>
            <input type="text" id="verify-code" name="verify-code" required
              class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/20 transition-custom py-2 border"
              placeholder="请输入验证码">
          </div>
          <div class="flex items-end">
            <button type="button" id="send-code"
              class="bg-secondary hover:bg-primary text-white font-medium py-2 px-4 rounded-lg transition-custom whitespace-nowrap">
              获取验证码
            </button>
          </div>
        </div>
        <div id="password-fields" class="hidden space-y-4">
          <div>
            <label for="new-password" class="block text-sm font-medium text-gray-700 mb-1">新密码</label>
            <input type="password" id="new-password" name="new-password"
              class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/20 transition-custom py-2 border"
              placeholder="请输入新密码">
          </div>
          <div>
            <label for="confirm-password" class="block text-sm font-medium text-gray-700 mb-1">确认新密码</label>
            <input type="password" id="confirm-password" name="confirm-password"
              class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary/20 transition-custom py-2 border"
              placeholder="请确认新密码">
          </div>
        </div>
        <div class="flex gap-3">
          <button type="button" id="close-modal"
            class="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-800 font-medium py-2 px-4 rounded-lg transition-custom">
            取消
          </button>
          <button type="submit"
            class="flex-1 bg-primary hover:bg-primary/90 text-white font-medium py-2 px-4 rounded-lg transition-custom">
            确认
          </button>
        </div>
      </form>
    </div>
  </div>

  <script>
    // 全局变量（不变）
    let currentUser = null;
    let queryHistory = [];
    let isResetPassword = false;

    // DOM元素（不变）
    const loginPage = document.getElementById('login-page');
    const servicePage = document.getElementById('service-page');
    const loginForm = document.getElementById('login-form');
    const queryForm = document.getElementById('query-form');
    const questionInput = document.getElementById('question-input');
    const answerContainer = document.getElementById('answer-container');
    const historyContainer = document.getElementById('history-container');
    const clearHistoryBtn = document.getElementById('clear-history');
    const logoutBtn = document.getElementById('logout-btn');
    const togglePasswordBtn = document.getElementById('toggle-password');
    const passwordInput = document.getElementById('password');
    const forgotPasswordBtn = document.getElementById('forgot-password');
    const registerBtn = document.getElementById('register');
    const verifyModal = document.getElementById('verify-modal');
    const closeModalBtn = document.getElementById('close-modal');
    const verifyForm = document.getElementById('verify-form');
    const sendCodeBtn = document.getElementById('send-code');
    const modalTitle = document.getElementById('modal-title');
    const passwordFields = document.getElementById('password-fields');
    const exampleQuestions = document.querySelectorAll('.example-question');

    // 初始化（不变）
    function init() {
      const savedUser = localStorage.getItem('currentUser');
      if (savedUser) {
        currentUser = JSON.parse(savedUser);
        showServicePage();
      } else {
        showLoginPage();
      }
      loadQueryHistory();
    }

    // 显示登录/服务页面（不变）
    function showLoginPage() {
      loginPage.classList.remove('hidden');
      servicePage.classList.add('hidden');
    }
    function showServicePage() {
      loginPage.classList.add('hidden');
      servicePage.classList.remove('hidden');
      renderQueryHistory();
    }

    // 切换密码可见性（不变）
    togglePasswordBtn.addEventListener('click', () => {
      const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
      passwordInput.setAttribute('type', type);
      togglePasswordBtn.querySelector('i').classList.toggle('fa-eye');
      togglePasswordBtn.querySelector('i').classList.toggle('fa-eye-slash');
    });

    // -------------------------- 1. 登录表单提交（只处理登录，移除查询逻辑） --------------------------
    loginForm.addEventListener('submit', (e) => {
      e.preventDefault(); // 阻止表单默认提交
      const username = document.getElementById('username').value.trim();
      const password = passwordInput.value.trim();

      // 先做简单前端校验
      if (!username || !password) {
        alert('账号和密码不能为空！');
        return;
      }

      // 调用后端登录接口
      fetch('http://47.120.77.67:5000/api/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username: username, password: password })
      })
      .then(response => {
        // 处理后端返回的JSON格式（若后端返回非JSON，这里会报错，需捕获）
        if (!response.ok) throw new Error('登录请求失败');
        return response.json();
      })
      .then(data => {
        if (data.success) {
          // 登录成功：保存用户状态，跳转到服务页面
          currentUser = { username };
          localStorage.setItem('currentUser', JSON.stringify(currentUser));
          showServicePage();
          loginForm.reset(); // 重置登录表单
        } else {
          // 登录失败：提示后端返回的错误信息
          alert(data.message || '登录失败，请检查账号密码！');
        }
      })
      .catch(error => {
        // 网络错误或接口异常
        alert('登录失败，请检查后端服务是否已启动！');
        console.error('登录错误详情：', error);
      });
    });

    // -------------------------- 2. 查询表单提交（只处理查询，单独绑定事件） --------------------------
    queryForm.addEventListener('submit', (e) => {
      e.preventDefault(); // 阻止表单默认提交
      const question = questionInput.value.trim();

      // 先做简单前端校验
      if (!question) {
        alert('请输入查询问题！');
        return;
      }

      // 显示加载状态（提升用户体验）
      answerContainer.innerHTML = '<div class="text-center py-12"><i class="fa fa-circle-o-notch fa-spin text-4xl text-primary"></i><p class="mt-2 text-gray-600">查询中...</p></div>';

      // 调用后端查询接口
      fetch('http://47.120.77.67:5000/api/query', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ question: question }) // 传递用户输入的问题
      })
      .then(response => {
        if (!response.ok) throw new Error('查询请求失败');
        return response.json();
      })
      .then(data => {
        // 显示查询结果（用<pre>保留后端返回的换行格式）
        answerContainer.innerHTML = `<pre class="text-gray-700 whitespace-pre-wrap">${data.answer || '未找到相关信息，请尝试其他问题！'}</pre>`;
        // 将问题加入查询历史
        addToQueryHistory(question);
        // 清空输入框
        questionInput.value = '';
      })
      .catch(error => {
        // 网络错误或接口异常
        answerContainer.innerHTML = '<pre class="text-red-500">查询失败，请检查后端服务是否已启动！</pre>';
        console.error('查询错误详情：', error);
      });
    });

    // -------------------------- 以下是查询历史、退出登录等逻辑（不变，保留） --------------------------
    // 添加到查询历史
    function addToQueryHistory(question) {
      if (!queryHistory.includes(question)) {
        queryHistory.unshift(question);
        if (queryHistory.length > 20) queryHistory.pop();
        saveQueryHistory();
        renderQueryHistory();
      }
    }

    // 加载/保存/渲染查询历史（不变）
    function loadQueryHistory() {
      const savedHistory = localStorage.getItem('queryHistory');
      if (savedHistory) queryHistory = JSON.parse(savedHistory);
    }
    function saveQueryHistory() {
      localStorage.setItem('queryHistory', JSON.stringify(queryHistory));
    }
    function renderQueryHistory() {
      if (queryHistory.length === 0) {
        historyContainer.innerHTML = '<div class="text-gray-400 text-center py-6 text-sm">暂无查询历史</div>';
        return;
      }
      historyContainer.innerHTML = '';
      queryHistory.forEach(question => {
        const historyItem = document.createElement('div');
        historyItem.className = 'p-3 bg-gray-50 rounded-lg border border-gray-100 hover:bg-gray-100 cursor-pointer transition-custom';
        historyItem.innerHTML = `<p class="text-sm line-clamp-2">${question}</p>`;
        historyItem.addEventListener('click', () => {
          questionInput.value = question;
          questionInput.focus();
        });
        historyContainer.appendChild(historyItem);
      });
    }

    // 清空查询历史（不变）
    clearHistoryBtn.addEventListener('click', () => {
      if (confirm('确定要清空查询历史吗？')) {
        queryHistory = [];
        saveQueryHistory();
        renderQueryHistory();
      }
    });

    // 退出登录（不变）
    logoutBtn.addEventListener('click', () => {
      if (confirm('确定要退出登录吗？')) {
        localStorage.removeItem('currentUser');
        currentUser = null;
        showLoginPage();
      }
    });

    // 验证码模态框相关逻辑（不变，保留）
    forgotPasswordBtn.addEventListener('click', () => {
      isResetPassword = true;
      modalTitle.textContent = '修改密码';
      passwordFields.classList.remove('hidden');
      verifyModal.classList.remove('hidden');
    });
    registerBtn.addEventListener('click', () => {
      isResetPassword = false;
      modalTitle.textContent = '注册新用户';
      passwordFields.classList.remove('hidden');
      verifyModal.classList.remove('hidden');
    });
    closeModalBtn.addEventListener('click', () => {
      verifyModal.classList.add('hidden');
      verifyForm.reset();
    });
    sendCodeBtn.addEventListener('click', () => {
      const phone = document.getElementById('phone').value;
      if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
        alert('请输入正确的手机号码');
        return;
      }
      let countdown = 60;
      sendCodeBtn.disabled = true;
      sendCodeBtn.textContent = `重新发送(${countdown}s)`;
      const timer = setInterval(() => {
        countdown--;
        sendCodeBtn.textContent = `重新发送(${countdown}s)`;
        if (countdown <= 0) {
          clearInterval(timer);
          sendCodeBtn.disabled = false;
          sendCodeBtn.textContent = '获取验证码';
        }
      }, 1000);
      console.log(`向${phone}发送验证码`);
    });
    verifyForm.addEventListener('submit', (e) => {
      e.preventDefault();
      const phone = document.getElementById('phone').value;
      const code = document.getElementById('verify-code').value;
      const newPassword = document.getElementById('new-password').value;
      const confirmPassword = document.getElementById('confirm-password').value;

      if (!phone || !code) {
        alert('请输入手机号码和验证码');
        return;
      }
      if (!newPassword || !confirmPassword) {
        alert('请输入并确认新密码');
        return;
      }
      if (newPassword !== confirmPassword) {
        alert('两次输入的密码不一致');
        return;
      }

      alert(isResetPassword ? '密码修改成功' : '注册成功');
      verifyModal.classList.add('hidden');
      verifyForm.reset();
    });

    // 问题示例点击填充（不变）
    exampleQuestions.forEach(example => {
      example.addEventListener('click', () => {
        questionInput.value = example.querySelector('p').textContent;
        questionInput.focus();
      });
    });

    // 点击模态框外部关闭（不变）
    verifyModal.addEventListener('click', (e) => {
      if (e.target === verifyModal) {
        verifyModal.classList.add('hidden');
        verifyForm.reset();
      }
    });

    // 页面加载初始化（不变）
    document.addEventListener('DOMContentLoaded', init);
  </script>
</body>
</html>